package com.xnx.bincker.leader.service.impl;

import com.xnx.bincker.leader.dao.MenuRepository;
import com.xnx.bincker.leader.domain.Authority;
import com.xnx.bincker.leader.domain.Menu;
import com.xnx.bincker.leader.service.AuthorityService;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.Collection;
import java.util.List;

@Service
public class AuthorityServiceImpl extends BasicServiceImpl<Authority, String> implements AuthorityService {
    private final MenuRepository menuRepository;
    AuthorityServiceImpl(MenuRepository menuRepository) {
		this.menuRepository = menuRepository;
	}

    /**
     * 删除前解除菜单关联
     */
    public void deleteInBatch(Collection<Authority> authorities) {
        if(authorities.isEmpty()) return;
        List<Menu> menuList = menuRepository.findAll(((root, criteriaQuery, criteriaBuilder) -> {
            CriteriaBuilder.In<Authority> authorityIn = criteriaBuilder.in(root.get("authority"));
            authorities.forEach(authorityIn::value);
            return criteriaBuilder.and(authorityIn);
        }));
        menuList.forEach(menu -> menu.setAuthority(null));
        menuRepository.saveAll(menuList);
        menuRepository.flush();
        super.deleteInBatch(authorities);
    }

}
